<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 17-9-14
 * Time: 上午11:21
 */

namespace app\controller;




use app\common\MobileSMS;
use app\common\weixin;
use app\model\AgentList;
use app\model\CardList;
use app\model\CardPackageList;
use app\model\OrderList;
use app\model\SupplyList;
use app\model\UserCardList;
use app\model\UserList;
use think\Db;
use think\Request;

/**
 * @property OrderList OrderList
 * @property UserList UserList
 * @property UserCardList UserCardList
 * @property CardList CardList
 * @property CardPackageList CardPackageList
 * @property AgentList AgentList
 * @property SupplyList SupplyList
 */
class Orders extends CommonController
{

    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->OrderList = new OrderList();
        $this->UserList = new UserList();
        $this->UserCardList = new UserCardList();
        $this->CardList = new CardList();
        $this->CardPackageList = new CardPackageList();
        $this->AgentList = new AgentList();
        $this->SupplyList = new SupplyList();


    }
    function order_list()
    {
        $card_list = $this->CardList->where(["status"=>0])->order("card_no asc")->select();
        $user_ids = $this->UserList->field("id,real_name,mobile")->select();
        $supply_list = $this->SupplyList->where(["status"=>0])->field("supply_code,supply_name")->select();
        $agent_list = $this->AgentList->field("id,agent_name")->select();
        $card_package_list = $this->CardPackageList
            ->where(["status"=>0])
            ->order("id desc")
            ->select();
        $this->assign("agent_list",$agent_list);
        $this->assign("user_ids",$user_ids);
        $this->assign("supply_list",$supply_list);
        $this->assign("card_list",$card_list);
        $this->assign("card_package_list",$card_package_list);
        $this->assign("page_title","订单列表");
        return $this->fetch();
    }
    function ajax_order_list()
    {
        try
        {
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $order_no = input("order_no","","trim");
            $third_no = input("third_no","","trim");
            $card_no = input("card_no","","trim");
            $user_mobile = input("user_mobile","","trim");
            $mobile = input("mobile","","trim");
            $supply_code = input("supply_code","","trim");
            $agent_id = input("agent_id",0,"intval");
            $mode = input("mode",-1,"intval");
            $card_type = input("card_type",-1,"intval");
            $pay_type = input("pay_type",-1,"intval");
            $pay_status = input("pay_status",-1,"intval");
            $delivery_status = input("delivery_status",-1,"intval");
            $is_rebate = input("is_rebate",-1,"intval");
            $status = input("status",-1,"intval");
            $date_1 = input("date_1",get_date_time("Y-m-d"),"trim");
            $date_2 = input("date_2",get_date_time("Y-m-d"),"trim");
            if($date_1 > $date_2)
                $this->E("选择日期出错");
            $date_1 = strtotime($date_1);

            if(empty($date_1))
                $date_1 = strtotime("today");
            $date_2 = strtotime($date_2);
            if(empty($date_2))
                $date_2 = strtotime("today");
            $where = [];
            if(!empty($order_no))
                $where["ol.order_no"] = $order_no;
            if(!empty($third_no))
                $where["ol.third_no"] = $third_no;
            if(!empty($card_no))
                $where["ol.card_no"] = ["like","%".$card_no."%"];
            if(!empty($user_mobile))
                $where["ul.mobile"] = $user_mobile;
            if(!empty($mobile))
                $where["ol.mobile"] = $mobile;
            if(!empty($supply_code))
                $where["ol.supply_code"] = $supply_code;
            if(!empty($agent_id))
                $where["ol.agent_id"] = $agent_id;
            if(in_array($mode,[0,1]))
                $where["ol.mode"] = $mode;
            if(in_array($card_type,[0,1,2]))
                $where["ol.card_type"] = $card_type;
            if(in_array($pay_type,[0,1,2,3,4,5,6]))
                $where["ol.pay_type"] = $pay_type;
            if(in_array($pay_status,[0,1,2,3,4]))
                $where["ol.pay_status"] = $pay_status;
            if(in_array($delivery_status,[0,1,2,3]))
                $where["ol.delivery_status"] = $delivery_status;
            if(in_array($status,[0,1,2,3]))
                $where["ol.status"] = $status;
            if(in_array($is_rebate,[0,1]))
                $where["ol.is_rebate"] = $is_rebate;
            $where["ol.ctime"] = ["between",[$date_1,$date_2+86400-1]];
            $where["ol.is_delete"] = 0;
            $count = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_supply_list sl" ,"sl.supply_code=ol.supply_code","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->join("f_supply_list sl" ,"sl.supply_code=ol.supply_code","left")
                ->where($where)
                ->field("ol.*,ul.mobile as user_mobile,cpl.name as product_name,al.agent_name,sl.supply_name")
                ->order("ol.ctime desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();

            $money_list = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->where($where)
                ->field(['sum(if(ol.pay_status=1,ol.total_money,0)) as count_total_money',
                    'sum(if(ol.status=2 and ol.pay_status=1,ol.cost,0)) as count_cost',
                    'sum(if(ol.status=2 and ol.pay_status=1,ol.card_fee,0)) as count_card_fee',
                    'sum(if(ol.status=2 and ol.pay_status=1,ol.total_money-ol.card_fee-ol.freight-ol.cost-ol.agent_rebate,0)) as count_profit',
                    'sum(if(ol.pay_type=3 and ol.pay_status=1,ol.supply_cost,0)) as count_pay_supply_cost',
                    'sum(if(ol.status=2 and ol.pay_status=1,ol.supply_cost,0)) as count_supply_cost',
                    'sum(if(ol.status=2 and ol.pay_status=1,ol.agent_rebate,0)) as count_agent_rebate'
                    ])
                ->find();
            $this->resultdata["money_list"] = $money_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_export_order_list()
    {
        try
        {
            if ($dh = opendir("./files")){
                while (($file = readdir($dh)) !== false){

                    if(stripos($file,"order_list-".$this->admin_id."-") !== false)
                        @unlink("./files/".$file);
                }
                closedir($dh);
            }
            $order_no = input("order_no","","trim");
            $third_no = input("third_no","","trim");
            $card_no = input("card_no","","trim");
            $user_mobile = input("user_mobile","","trim");
            $mobile = input("mobile","","trim");
            $agent_id = input("agent_id",0,"intval");
            $pay_type = input("pay_type",0,"intval");
            $pay_status = input("pay_status",0,"intval");
            $delivery_status = input("delivery_status",0,"intval");
            $status = input("status",0,"intval");
            $date_1 = input("date_1",get_date_time("Y-m-d"),"trim");
            $date_2 = input("date_2",get_date_time("Y-m-d"),"trim");
            if($date_1 > $date_2)
                $this->E("选择日期出错");

            $date_1 = strtotime($date_1);

            if(empty($date_1))
                $date_1 = strtotime("today");
            $date_2 = strtotime($date_2);
            if(empty($date_2))
                $date_2 = strtotime("today");
            $where = [];
            if(!empty($order_no))
                $where["ol.order_no"] = $order_no;
            if(!empty($third_no))
                $where["ol.third_no"] = $third_no;
            if(!empty($card_no))
                $where["ol.card_no"] = $card_no;
            if(!empty($user_mobile))
                $where["ul.mobile"] = $user_mobile;
            if(!empty($mobile))
                $where["ol.mobile"] = $mobile;
            if(!empty($agent_id))
                $where["ol.agent_id"] = $agent_id;
            if(in_array($pay_type,[0,1,2,3,4]))
                $where["ol.pay_type"] = $pay_type;
            if(in_array($pay_status,[0,1,2,3]))
                $where["ol.pay_status"] = $pay_status;
            if(in_array($delivery_status,[0,1,2,3]))
                $where["ol.delivery_status"] = $delivery_status;
            if(in_array($status,[0,1,2,3]))
                $where["ol.status"] = $status;
            $where["ol.ctime"] = ["between",[$date_1,$date_2+86400-1]];
            $where["ol.is_delete"] = 0;

            $order_log = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->where($where)
                ->field("ol.*,ul.mobile as user_mobile,cpl.name as product_name,al.agent_name")
                ->order("ol.ctime desc")
                ->select();
            $headers = ["时间","订单ID","订单号","支付订单号","用户账号","卡代理","卡号","卡类型","套餐名称","原始价格","成本价格","价格","运费","卡费","总价格","充值面额","充值成本","类型","支付方式","支付状态","状态","发货状态","是否返佣"];
            $filename = '/files/order_list-'.$this->admin_id.'-'.NOW_TIME.'.csv';
            $fp = @fopen(".".$filename, 'w');
            @fwrite($fp,chr(0xEF).chr(0xBB).chr(0xBF));
            @fputcsv($fp, $headers);
            foreach ($order_log as $key=>$val)
            {
                $info = [
                    date("Y-m-d H:i:s",$val["ctime"])."\t",
                    $val["order_id"]."\t",
                    $val["order_no"]."\t",
                    $val["pay_order_no"]."\t",
                    $val["user_mobile"]."\t",
                    $val["agent_name"]."\t",
                    $val["card_no"]."\t",
                    get_card_type($val["card_type"]),
                    $val["product_name"],
                    number_format($val["basic_price"]/10000, 2, '.', ''),
                    number_format($val["cost"]/10000, 2, '.', ''),
                    number_format($val["money"]/10000, 2, '.', ''),
                    number_format($val["freight"]/10000, 2, '.', ''),
                    number_format($val["card_fee"]/10000, 2, '.', ''),
                    number_format($val["total_money"]/10000, 2, '.', ''),
                    number_format($val["supply_basic_price"]/10000, 2, '.', ''),
                    number_format($val["supply_cost"]/10000, 2, '.', ''),
                    get_mode($val["mode"]),
                    get_pay_type($val["pay_type"]),
                    get_pay_status($val["pay_status"]),
                    get_status($val["status"]),
                    get_delivery_status($val["delivery_status"]),
                    get_yes_no($val["is_rebate"]),
                ];
                @fputcsv($fp, $info);
            }
            @fclose($fp);
            if(!is_file(".".$filename))
            {
                $this->E("导出异常");
            }
            $this->resultdata["data"]["filename"] = $filename;
            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_order_info()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            $is_delivery = input("is_delivery",0,"intval");
            if(empty($order_id))
                $this->E("参数不能为空");
            $info = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->where(["ol.order_id"=>$order_id])->field("ol.*,ul.real_name as user_name,cpl.name as product_name,al.agent_name,al.agent_info")->find();
            $order_no = !empty($info["order_no"])?$info["order_no"]:"";
            $order_log_list = $this->OrderLog->alias("ol")
                ->join("f_admin a","a.id=ol.admin_id","left")
                ->where(["ol.order_no"=>$order_no])
                ->order("ol.ctime desc,ol.id desc")
                ->field("ol.*,a.real_name as admin_name")
                ->select();
            $corp_code = "";
            if(!empty($is_delivery)&&!empty($info["express_no"]))
            {
                $express_no = preg_replace("# #","",$info["express_no"]);
                $express_name = trim($info["express_name"]);


                if(strpos($express_name,"韵达") !== false)
                {
                    $corp_code = "yunda";
                }elseif(strpos($express_name,"顺丰") !== false)
                {
                    $corp_code = "shunfeng";
                }elseif(strpos($express_name,"申通") !== false)
                {
                    $corp_code = "shentong";
                }elseif(strpos($express_name,"圆通") !== false)
                {
                    $corp_code = "yuantong";
                }elseif(strpos($express_name,"中通") !== false)
                {
                    $corp_code = "zhongtong";
                }elseif(strpos($express_name,"EMS") !== false)
                {
                    $corp_code = "ems";
                }
                if($corp_code)
                {
                    $url = "http://baidu.kuaidi100.com/query";
                    $delivery_list_obj = curl_url($url,[],"type=".$corp_code."&postid=".$express_no."&id=4&valicode=&temp=".NOW_TIME);
                    if(!empty($delivery_list_obj) &&$delivery_list_obj["code"] == 200)
                    {
                        $info["delivery_list"] = json_decode($delivery_list_obj["body"],true);
                        if($info["delivery_list"]["status"] =="200" &&$info["delivery_list"]["state"] =="3" &&$info["delivery_list"]["nu"] == $express_no)
                        {
                            $query = $this->OrderList->where(["delivery_status"=>2,"order_no"=>$order_no])->update(["delivery_status"=>3]);
                            if($query)
                            {
                                $info["delivery_status"]  =3;
                            }
                        }
                    }
                }
//                $delivery_list_obj = curl_url("http://www.kuaidi100.com/query?type=yunda&postid=".$express_no."&temp=0.".time());
//                if(!empty($delivery_list_obj) &&$delivery_list_obj["code"] == 200)
//                {
//                    $info["delivery_list"] = json_decode($delivery_list_obj["body"],true);
//                }

            }
            $info["corp_code"] = $corp_code;
            $info["order_log_list"] = $order_log_list;
            $this->resultdata["data"] = $info;
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_user_card_list()
    {
        try
        {
            $user_id = input("user_id",0,"intval");
            if(empty($user_id))
            {
                $info = $this->UserCardList->where(["status"=>1])->select();
            }else{
                $info = $this->UserCardList->where(["user_id"=>$user_id,"status"=>1])->select();
            }


            $this->resultdata["data"] = $info;
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    function ajax_add_card()
    {
        try
        {
            $user_id = input("user_id",0,"intval");
            $agent_id = input("agent_id",0,"intval");
            $card_no = input("card_no","","trim");
            $product_id = input("product_id",0,"intval");
            $freight = input("freight",0,"intval");
            $card_fee = input("card_fee",0,"intval");
            $discount_money = input("discount_money",0,"intval");
            $real_name = input("real_name","","trim");
            $address = input("address","","trim");
            $mobile = input("mobile","","trim");

            if( empty($product_id) ||empty($card_no)||empty($real_name)||empty($address)||empty($mobile))
                $this->E("参数不正确");
            $freight =$freight*10000;
            $card_fee =$card_fee*10000;
            $discount_money =$discount_money*10000;
            $card_package_info = $this->CardPackageList
                ->where(["status"=>0,"id"=>$product_id,"mode"=>1])
                ->order("id desc")
                ->find();
            if(empty($card_package_info))
                $this->E("套餐不存在");
            if(!empty($agent_id))
            {
                $agent_info = $this->AgentList->where(["id"=>$agent_id])->find();
                if(empty($agent_info))
                    $this->E("代理不存在");
            }

            $card_type = $card_package_info["card_type"];
            $goods_id = $card_package_info["goods_id"];
            $basic_price = $card_package_info["basic_price"];
            $cost = $card_package_info["cost"];
            $money = $card_package_info["money"];
            $mode = $card_package_info["mode"];
            $order_no = get_order_no("D");
            $total_money = $money+$freight+$card_fee-$discount_money;
            $info = [
                "order_no" => $order_no,
                "user_id" => $user_id,
                "agent_id" => $agent_id,
                "card_no" =>$card_no,
                "card_type" =>$card_type,
                "product_id" => $product_id,
                "goods_id" =>$goods_id,
                "basic_price"=>$basic_price,
                "cost" => $cost,
                "money" => $money,
                "freight" =>$freight,
                "card_fee" => $card_fee,
                "discount_money"=>$discount_money,
                "total_money" =>$total_money,
                "mode" =>$mode,
                "real_name"=>$real_name,
                "address" =>$address,
                "mobile" => $mobile,
                "ctime" => NOW_TIME,
                "mtime" => NOW_TIME,
                "ip" => $this->request->ip()
            ];
            if(!empty($user_id))
            {
                $user_info = $this->UserList->where(["id"=>$user_id])->find();
                if(empty($user_info))
                    $this->E("用户不存在");
            }else{
                $user_info = $this->UserList->where(["mobile"=>$mobile])->find();
                if(!empty($user_info))
                {
                    $user_id = $user_info["id"];
                }
                elseif(empty($user_info) &&is_mobile($mobile))
                {
                    $user_info = [
                        "real_name"=>$real_name,
                        "address" =>$address,
                        "mobile" => $mobile,
                        "ctime" =>NOW_TIME
                    ];
                    $user_id = $this->UserList->insertGetId($user_info);
                    if(empty($user_id))
                        $this->E("用户添加失败");
                }

            }

            $info["user_id"] = $user_id;


            Db::startTrans();
            try{
                $query = $this->CardList->where(["card_no" =>$card_no,"card_type"=>$card_type,"status"=>0])->update(["status"=>1]);
                if(empty($query))
                    $this->E("卡号不存在或已经使用");

                $query = $this->OrderList->insert($info);
                if(empty($query))
                    $this->E("添加订单失败");
                $query = $this->UserCardList->insert(["user_id"=>$user_id,"agent_id"=>$agent_id,"card_no"=>$card_no,"card_type"=>$card_type,"card_fee" => $card_fee,"status"=>1, "ctime" =>NOW_TIME]);
                if(empty($query))
                    $this->E("用户绑定卡片失败");

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->E($e->getMessage());
            }

            $this->order_log($order_no,"添加新卡订单，卡号：".$card_no);

            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_add_recharge()
    {
        try
        {
            $card_no = input("card_no","","trim");
            $product_id = input("product_id",0,"intval");
            $discount_money = input("discount_money",0,"intval");
            if( empty($product_id) ||empty($card_no))
                $this->E("参数不正确");
            $discount_money =$discount_money*10000;
            $card_package_info = $this->CardPackageList
                ->where(["status"=>0,"id"=>$product_id,"mode"=>["in",[0,2]]])
                ->order("id desc")
                ->find();
            if(empty($card_package_info))
                $this->E("套餐不存在");
            $card_type = $card_package_info["card_type"];
            $goods_id = $card_package_info["goods_id"];
            $basic_price = $card_package_info["basic_price"];
            $cost = $card_package_info["cost"];
            $money = $card_package_info["money"];
            $mode = $card_package_info["mode"];
            $order_no = get_order_no("D");
            $total_money = $money-$discount_money;
            if($mode == 1)
                $this->E("卡套餐选择错误");
            $info = [
                "order_no" => $order_no,
                "card_no" =>$card_no,
                "card_type" =>$card_type,
                "product_id" => $product_id,
                "goods_id" =>$goods_id,
                "basic_price"=>$basic_price,
                "cost" => $cost,
                "money" => $money,
                "discount_money"=>$discount_money,
                "total_money" =>$total_money,
                "mode" =>$mode,
                "ctime" => NOW_TIME,
                "mtime" => NOW_TIME,
                "ip" => $this->request->ip()
            ];
            if(!empty($card_no))
            {
                $user_card_info = $this->UserCardList->where(["card_no"=>$card_no])->find();
                if(empty($user_card_info))
                    $this->E("卡不存在");
                $info["card_no"] = $user_card_info["card_no"];
                $info["agent_id"] = $user_card_info["agent_id"];
                $info["company_id"] = $user_card_info["company_id"];
            }
            $card_info = $this->UserCardList->where(["card_no"=>$card_no,"status"=>1])->find();
            if(empty($card_info))
                $this->E("用户卡不存在或禁用");
            if($card_type != $card_info["card_type"])
            {
                $this->E("卡类型错误");
            }
            $user_id = $card_info["user_id"];
            if(!empty($user_id))
            {
                $user_info = $this->UserList->where(["id"=>$user_id])->find();
                if(empty($user_info))
                    $this->E("用户不存在");
            }
            $info["user_id"] = $user_id;

            Db::startTrans();
            try{

                $query = $this->OrderList->insert($info);
                if(empty($query))
                    $this->E("添加订单失败");


                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->E($e->getMessage());
            }


            $this->order_log($order_no,"添加充值订单，卡号：".$card_no);
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_send_order_log()
    {
        try
        {
            $order_no = input("order_no","","trim");
            $order_log_info = input("order_log_info","","trim");

            ;
            if(empty($order_no)||empty($order_log_info))
                $this->E("参数错误");
            $order_info = $this->OrderList->where(["order_no"=>$order_no])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $this->order_log($order_no,$order_log_info);
            $order_log_list = $this->OrderLog->alias("ol")
                ->join("f_admin a","a.id=ol.admin_id","left")
                ->where(["ol.order_no"=>$order_no])
                ->order("ol.ctime desc,ol.id desc")
                ->field("ol.*,a.real_name as admin_name")
                ->select();
            $this->resultdata["data"]["order_log_list"] = $order_log_list;
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_set_delivery()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            $express_name = input("express_name","","trim");
            $express_no = input("express_no","","trim");
            $delivery_status = input("delivery_status",0,"intval");
            if(empty($order_id))
                $this->E("参数错误");
            $order_info = $this->OrderList->where(["order_id"=>$order_id])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $order_no = $order_info["order_no"];
            $query = $this->OrderList->where(["order_id"=>$order_id,"pay_status"=>1])->update(["express_name"=>$express_name,"express_no"=>$express_no,"delivery_status"=>$delivery_status]);
            if(empty($query))
                $this->E("更新数据失败");
            $this->order_log($order_no,"修改发货信息，快递状态：".$delivery_status.",快递名称:".$express_name.",快递号:".$express_no);
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_send_delivery_msg()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            $express_name = input("express_name","","trim");
            $express_no = input("express_no","","trim");
            if(empty($order_id) ||empty($express_name)||empty($express_no))
                $this->E("参数错误");
            $order_info = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->where(["ol.order_id"=>$order_id])->field("ol.*,ul.mobile as user_mobile")->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $user_mobile = $order_info["user_mobile"];
            $order_no = $order_info["order_no"];
            if(empty($user_mobile))
                $this->E("手机号为空");
            if($order_info["token_type"] == 2 &&!empty($order_info["prepay_id"]))
            {
                $data = [
                    "keyword1"=> [
                        "value"=> "连连惠开卡充值".($order_info["basic_price"] / 10000)."元",
                        "color"=> "#000000"
                    ],
                    "keyword2"=> [
                        "value"=> date("Y-m-d H:i:s",NOW_TIME),
                        "color"=> "#000000"
                    ],
                    "keyword3"=> [
                        "value"=> $express_name,
                        "color"=> "#000000"
                    ] ,
                    "keyword4"=> [
                        "value"=> $express_no,
                        "color"=> "#000000"
                    ]
                ];
                $template_id = "htBlzvYGbM3UidixvKuP5WAo7QNi-yck9UYwcBLUkm0";
                $mp_open_id = $order_info["open_id"];
                $form_id = $order_info["prepay_id"];
//                $mp_open_id = "ok7DS5G7rKzTHLV6iXOIVqS_vCgE";
//                $form_id = "wx031550075808567b6d93cdb03801512041";
                $page = "pages/index/index";
                $weixin = new weixin();
                $query = $weixin->sendMPTemplate($mp_open_id,$template_id,$page,$form_id,$data);
            } else {
                $query = MobileSMS::sendMobileDelivery($user_mobile,$express_name,$express_no);
            }
            if(!$query)
                $this->E("发送失败");
            $this->order_log($order_no,"发送发货短信,快递名称:".$express_name.",快递号:".$express_no);
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_add_new_card()
    {
        $order_no = "";
        try
        {
            $order_id = input("order_id",0,"intval");
            $card_no = input("card_no","","trim");
            if(empty($order_id)||empty($card_no))
                $this->E("参数不能为空");
            $order_info = $this->OrderList->where(["order_id"=>$order_id])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $order_no = $order_info["order_no"];
            $user_id = $order_info["user_id"];
            $agent_id = $order_info["agent_id"];
            $card_type = $order_info["card_type"];
            $user_info = $this->UserList->where(["id"=>$user_id])->find();
            if($agent_id>0)
            {
                $agent_info = $this->AgentList->where(["id"=>$agent_id])->find();
                if(empty($agent_info))
                    $this->E("代理不存在");
            }

            Db::startTrans();
            try{
                $query = $this->CardList->where(["card_no" =>$card_no,"card_type"=>$card_type,"status"=>0])->update(["status"=>1]);
                if(empty($query))
                    $this->E("卡号不存在或已经使用");

                $query = $this->UserCardList->insert(["user_id"=>$user_id,"agent_id"=>$agent_id,"card_no"=>$card_no,"card_type"=>$card_type,"status"=>1, "ctime" =>NOW_TIME]);
                if(empty($query))
                    $this->E("用户绑定卡片失败");
                $query = $this->OrderList->where(["order_id"=>$order_id,"card_no"=>null])->update(["card_no"=>$card_no]);
                if(empty($query))
                    $this->E("更新数据失败，请联系技术");

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->E($e->getMessage());
            }



            $this->order_log($order_no,"添加订单卡号：".$card_no);
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->order_log($order_no,"添加订单卡号失败：".$e->getMessage());
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    /**
     * 修改订单付款状态为成功
     */
    function ajax_add_pay()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            if(empty($order_id))
                $this->E("参数不能为空");
            $order_info = $this->OrderList->where(["order_id"=>$order_id])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $order_no = $order_info["order_no"];
            $query = $this->OrderList->where(["order_id"=>$order_id,"pay_status"=>0])->update(["pay_status"=>1,"pay_type"=>0,"pay_time"=>NOW_TIME]);
            if(empty($query))
                $this->E("更新数据失败，请联系技术");
            $basic_price = $order_info["basic_price"];
            $money = $order_info["money"];
            $this->UserList->where(["id" => $order_info["user_id"]])->setInc("total_discount",$basic_price - $money);

            $this->order_log($order_no,"修改付款状态：成功");
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    /**
     * 修改订单付款状态为已取消
     */
    function ajax_cancel_pay()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            if(empty($order_id))
                $this->E("参数不能为空");
            $order_info = $this->OrderList->where(["order_id"=>$order_id])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $order_no = $order_info["order_no"];
            $query = $this->OrderList->where(["order_id"=>$order_id,"pay_status"=>0])->update(["pay_status"=>4,"pay_time"=>NOW_TIME]);
            if(empty($query))
                $this->E("更新数据失败，请联系技术");

            $this->order_log($order_no,"修改付款状态：成功");
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);

    }
    /**
     * 给订单充值
     */
    function ajax_recharge()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            if(empty($order_id))
                $this->E("参数错误");
            $result_data = $this->recharge($order_id);
            $this->resultdata = $result_data;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_order_notify_ext()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            if(empty($order_id))
                $this->E("参数错误");
            $info = $this->OrderList->alias("ol")
                ->where(["ol.order_id"=>$order_id,"ol.status"=>2,"ol.pay_status"=>1])
                ->field("ol.*")
                ->find();
            if(empty($info))
                $this->E("订单不存在或已经处理过");
            if(empty($info["card_no"]))
                $this->E("卡号不存在");
//            if(!empty($info["is_rebate"])&&!empty($info["is_sms"]))
//                $this->E("已经处理过");

            $order_no = $info["order_no"];
            $this->order_log($order_no,"订单后续处理");
//            if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//            {
//                exception("提交订单后续处理失败");
//            }
            if(!sendMQQueue("fuel_order_status",$order_no))
            {
                exception("提交订单后续处理失败");
            }
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_order_reply()
    {
        try
        {
            $order_id = input("order_id",0,"intval");
            if(empty($order_id))
                $this->E("参数错误");
            $info = $this->OrderList->alias("ol")
                ->where(["ol.order_id"=>$order_id])
                ->field("ol.*")
                ->find();
            if(empty($info))
                $this->E("订单不存在或已经处理过");
            if(empty($info["card_no"]))
                $this->E("卡号不存在");


            $order_no = $info["order_no"];
            $this->order_log($order_no,"订单回调");
//            if(!sendQueue("app\job\Orders::order_reply",[$order_no]))
//            {
//                exception("提交订单后续处理失败");
//            }
            if(!sendMQQueue("fuel_order_reply",$order_no))
            {
                exception("提交订单后续处理失败");
            }
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function recharge($order_id)
    {
        $result_data = ["error"=>1,"msg"=>"未知错误","data"=>[]];
        try
        {
            $info = $this->OrderList->alias("ol")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->where(["ol.order_id"=>$order_id,"ol.status"=>0])
                ->field("ol.*,cpl.goods_id")
                ->find();
            if(empty($info))
                $this->E("订单不存在或已经处理过");
//            if(empty($info["goods_id"]))
//                $this->E("上游商品不存在");
            if(empty($info["card_no"]))
                $this->E("卡号不存在");

            $order_no = $info["order_no"];
            $this->order_log($order_no,"提交充值");
//            if(!sendQueue("app\job\Orders::order_recharge",[$order_no]))
//            {
//                exception("提交充值订单失败");
//            }
            if(!sendMQQueue("fuel_order_recharge",$order_no))
            {
                exception("提交充值订单失败");
            }
//            $result = curl_url($this->recharge_url."?order_no=".$order_no."&is_echo=1",[]);
//            if(empty($result))
//                $this->E("提单失败1");
//            if($result["code"] != 200)
//                $this->E($result["error_info"]);
//            $result_body = json_decode($result["body"],true);
//            if($result_body["error"] == 1)
//                $this->E($result_body["msg"]);
            $result_data["error"] = 0;
        }catch (\Exception $e)
        {
            $result_data["msg"] = $e->getMessage();
        }
        return $result_data;
    }
    function ajax_refund_fee()
    {
        try
        {

            $order_id = input("order_id",0,"intval");
            $is_freight = input("is_freight",0,"intval");
            $is_card_fee = input("is_card_fee",0,"intval");
            $is_money = input("is_money",0,"intval");
            $refund_desc = input("refund_desc","","trim");
            if(empty($order_id))
                $this->E("参数错误");
            if(empty($is_freight)&&empty($is_card_fee)&&empty($is_money))
                $this->E("请选择退款类型");
            $order_info = $this->OrderList->where(["order_id"=>$order_id])->find();
            if(empty($order_info))
                $this->E("订单不存在");
            $pay_order_no = $order_info["pay_order_no"];
            $order_no = $order_info["order_no"];
            $card_fee = $order_info["card_fee"];
            $freight = $order_info["freight"];
            $money = $order_info["money"];
            $status = $order_info["status"];
            $total_money = $order_info["total_money"];
            $weixin = new weixin();
            $t_money = 0;
            $desc = [];
            $data = [];
            $data["total_money"] = $order_info["total_money"];

            if($order_info["pay_status"] != 1)
            {
                $this->E("非已付款订单");
            }
            if(!empty($is_freight)&&!empty($freight))
            {
                $t_money += $freight;
                $desc[] = "运费";
                $data["freight"] = 0;
                $data["total_money"] = $data["total_money"]-$freight;

            }
            if(!empty($is_card_fee)&&!empty($card_fee))
            {
                $t_money += $card_fee;
                $desc[] = "卡费";
                $data["card_fee"] = 0;
                $data["total_money"] = $data["total_money"]-$card_fee;
            }
            if(!empty($is_money)&&!empty($money))
            {
                if(!in_array($status,[0,3]))
                    exception("订单失败或未处理才能退款");
                $t_money += $money;
                $desc[] = "订单金额：".$money;
                $data["money"] = 0;
                $data["total_money"] = $data["total_money"]-$money;
//                $refund_desc="";
            }
            if(isset($data["total_money"]) &&$data["total_money"]<1)
                $data["pay_status"] = 3;
            if(empty($t_money))
                $this->E("退款金额为空");
            if(empty($pay_order_no))
                $this->E("非微信支付");
            $desc = "退还 ".implode("、",$desc);
            $query = $weixin->RefundOrder($pay_order_no,$total_money/100,$t_money/100,$refund_desc);
            if(!$query)
                $this->E("退款失败");
            $this->order_log($order_no,$desc.":".$t_money);
            $query=$this->OrderList->where(["order_id"=>$order_id,"pay_status"=>1])->update($data);
            if(!$query)
                $this->E("退款成功，更新数据失败");

            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();

        }

        echo json_encode($this->resultdata);
    }

    function appdatacount()
    {

        $this->assign("page_title","数据分析");
        return $this->fetch();
    }
    function ajax_appdatacount()
    {
        try
        {

            $startDate = input("startDate","","trim");
            $endDate = input("endDate","","trim");
            if(empty($startDate) ||empty($endDate))
                $this->E("参数不正常");
            if($startDate > $endDate)
                $this->E("选择日期出错");
            $startDate = strtotime($startDate);
            $endDate = strtotime($endDate);
            $where = [];
            $where["ctime"] = ["between",[$startDate,$endDate+86400-1]];
            $list = $this->OrderList->where($where)
                ->field(['COUNT(1)'=>'count_num',
                    'sum(if(pay_status=1,1,0))'=>'pay_num',
                    'sum(if(pay_status=1 and mode=0,1,0))'=>'mode_num_0',
                    'sum(if(pay_status=1 and mode=1,1,0))'=>'mode_num_1',
                    'sum(if(pay_status=1 and pay_type=1,1,0))'=>'weixin_num',
                    'FROM_UNIXTIME(ctime, "%Y-%m-%d")'=>"cc"])
                ->group("cc")->select();
            $date_list = [];
            $value_list = [];
            $list = make_array_key($list,"cc",true);
            $keys = ['count_num','pay_num','mode_num_0','mode_num_1','weixin_num'];

            for($i=$startDate;$i<=$endDate;$i=$i+86400)
            {
                $date =  date("Y-m-d",$i);
                $date_list[] = $date;

                foreach ($keys as $key)
                {
                    if(!empty($list[$date]))
                    {
                        $value_list[$key][] = intval($list[$date][$key]);
                    }else{
                        $value_list[$key][] = 0;

                    }
                }

            }


            $this->resultdata["data"]["date_list"] =$date_list;
            $this->resultdata["data"]["value_list"] = $value_list;
            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
}